package mo.leetcode_hot;

public class L581 {

    public int findUnsortedSubarray(int[] nums) {
        int n = nums.length;
        if (n == 1) {
            return 0;
        }
        int maxLeft = nums[0];
        int minRight = nums[n-1];
        int posR = -1;
        int posL = -1;
        for (int i = 1; i < n; i++) {
            if (nums[i] < maxLeft) {
                posR = i;
            } else {
                maxLeft = nums[i];
            }
        }
        if (posR == -1) {
            return 0;
        }
        for (int i = n-2; i >= 0; i--) {
            if (nums[i] > minRight) {
                posL = i;
            } else {
                minRight = nums[i];
            }
        }
        return posR - posL + 1;
    }

    public static void main(String[] args) {
        L581 test = new L581();
        System.out.println(test.findUnsortedSubarray(new int[]{1, 3, 2, 2, 2}));
    }
}
